package com.xxx.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxx.server.config.security.component.JwtTokenUtil;
import com.xxx.server.entity.RespBean;
import com.xxx.server.entity.User;
import com.xxx.server.mapper.UserMapper;
import com.xxx.server.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/*
        服务实现类
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired(required = false)
    private UserMapper userMapper;
    @Value("${jwt.tokenHead}")  //取tokenHead
    private String tokenHead;   //设置一个token头部信息
    @Override
    public RespBean login(String username, String password, String code, HttpServletRequest request) {

        String captcha = (String)request.getSession().getAttribute("captcha");   //获取从前端传来的验证码的值,并强转
        if (StringUtils.isEmpty(code) || !captcha.equalsIgnoreCase(code)){  //如果code为空或者匹配不上
            return RespBean.error("验证码输入有误，请重新输入");
        }
        //通过前端传来的用户名来加载数据库里面的用户信息，用来与前端传来的密码进行比对
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if (null == userDetails || !password.equals(userDetails.getPassword()) ){
            //!passwordEncoder.matches(password,userDetails.getPassword())
            return RespBean.error("用户名或密码错误");
        }
        if (!userDetails.isEnabled()){
            return RespBean.error("账号未启用");
        }
        //更新security登录用户对象      Authentication:认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails,
                null,userDetails.getAuthorities());//credentials：密码，一般不要放
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);//更新token
        //验证通过后，根据用户信息生成token
        String token = jwtTokenUtil.generateToken(userDetails);
        //设置token集合，并设置信息
        Map<String,String> tokenMap = new HashMap<>();
        tokenMap.put("token",token);
        tokenMap.put("tokenHead",tokenHead);
        return RespBean.success("登陆成功",tokenMap);
    }
    //根据用户名获取用户信息
    @Override
    public User getUserByUsername(String username) {
        return userMapper.selectOne( new QueryWrapper<User>().eq("username",username).eq("enabled",1));
        //查询到用户名，并存储在username；判断是不是禁用
    }
}
